import uuid
from calendar import timegm
from datetime import datetime

from rest_framework_jwt.compat import get_username_field, get_username
from rest_framework_jwt.settings import api_settings

from users.models import UserProfile


def jwt_payload_handler(user):
    username_field = get_username_field()
    username = get_username(user)

    user_1 = UserProfile.objects.filter(id=user.id)
    user_role = None
    if user_1.count() > 0:
        user_group = user_1[0].groups.all()
        if user_group.count() > 0:
            user_role = user_group[0].name
            print(user_role)

    # warnings.warn(
    #     'The following fields will be removed in the future: '
    #     '`email` and `user_id`. ',
    #     DeprecationWarning
    # )
    payload = {
        'user_id': user.pk,
        'username': username,
        'user_role': user_role,
        'mobile': user.mobile,
        'company_name': user.company_name
    }
    # if hasattr(user, 'email'):
    #     payload['email'] = user.email
    if isinstance(user.pk, uuid.UUID):
        payload['user_id'] = str(user.pk)

    payload[username_field] = username

    # Include original issued at time for a brand new token,
    # to allow token refresh
    if api_settings.JWT_ALLOW_REFRESH:
        payload['orig_iat'] = timegm(
            datetime.utcnow().utctimetuple()
        )

    # 接收方
    if api_settings.JWT_AUDIENCE is not None:
        payload['aud'] = api_settings.JWT_AUDIENCE

    # 签发者
    if api_settings.JWT_ISSUER is not None:
        payload['iss'] = api_settings.JWT_ISSUER

    return payload



